package flc.ast.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.ZipUtils;

import java.io.IOException;
import java.util.Locale;
import java.util.Random;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityFileCompressFuncBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.constant.Extra;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.UriUtil;

public class FileCompressFuncActivity extends BaseAc<ActivityFileCompressFuncBinding> {

    private String mFilePath;
    private String mFileName;
    private String mFileNameNoExtension;

    public static void start(Context context, String path) {
        Intent intent = IntentUtil.getIntent(context, FileCompressFuncActivity.class);
        intent.putExtra(Extra.PATH, path);
        context.startActivity(intent);
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_file_compress_func;
    }

    @Override
    protected void initView() {
        mDataBinding.ivFileCompressFuncBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mFilePath = getIntent().getStringExtra(Extra.PATH);
        mFileName = FileUtils.getFileName(mFilePath);
        mFileNameNoExtension = FileUtils.getFileNameNoExtension(mFilePath);
        mDataBinding.tvName.setText(mFileName);

        int progress = new Random().nextInt(55);
        mDataBinding.sbProgress.setProgress(progress);
        mDataBinding.sbProgress.postDelayed(new Runnable() {
            @Override
            public void run() {
                compressFiles();
            }
        }, 1500);
        mDataBinding.ivGoOn.setOnClickListener(this);
        mDataBinding.ivConfirm.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivGoOn:
                StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_compress_permission)).callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        mDataBinding.sbProgress.setProgress(0);
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("*/*");
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        try {
                            startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 120);
                        } catch (android.content.ActivityNotFoundException ex) {
                        }
                    }
                }).request();
                break;
            case R.id.ivConfirm:
                onBackPressed();
                break;
        }
    }

    @Override
    protected void initData() {

    }


    private void compressFiles() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            private String zipPath;

            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                zipPath = FileUtil.generateFilePath(Content.MyCompress, ".zip");
                try {
                    boolean zipResult = ZipUtils.zipFile(mFilePath, zipPath);

                    int index = mFileName.lastIndexOf(".");
                    FileUtils.rename(zipPath, mFileName.substring(0, index) + ".zip");
                    emitter.onNext(zipResult);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void accept(Boolean obj) {
                if (obj) {
                    mDataBinding.ivIcon.setImageResource(R.drawable.ayasuobao);
//                    mDataBinding.tvName.setText(FileUtils.getFileName(zipPath));
                    int index = mFileName.lastIndexOf(".");
                    mDataBinding.tvName.setText(mFileName.substring(0, index) + ".zip");
                    mDataBinding.tvTips.setText(R.string.compress_success_tips);
                    mDataBinding.sbProgress.setProgress(100);
                    mDataBinding.llSuccess.setVisibility(View.VISIBLE);
                } else {
                    ToastUtils.showShort(R.string.no_compress_hint);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 120) {
                Uri audioUri = data.getData();
                if (audioUri == null) {
                    return;
                }
                String selPath = UriUtil.uri2File(audioUri).getPath();
                if (FileUtils.getFileExtension(selPath).toLowerCase(Locale.ROOT).equals("zip") || FileUtils.getFileExtension(selPath).toLowerCase(Locale.ROOT).equals("rar")) {
                    ToastUtils.showShort(R.string.already_compress_file_tips);
                } else {
                    mFilePath = selPath;
                    mFileName = FileUtils.getFileName(mFilePath);
                    mFileNameNoExtension = FileUtils.getFileNameNoExtension(mFilePath);
                    mDataBinding.tvName.setText(mFileName);
                    mDataBinding.ivIcon.setImageResource(R.drawable.awenjian);
                    mDataBinding.llSuccess.setVisibility(View.GONE);
                    int progress = new Random().nextInt(55);
                    mDataBinding.sbProgress.setProgress(progress);
                    mDataBinding.sbProgress.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            compressFiles();
                        }
                    }, 1500);
                }
            }
        }
    }
}